package com.tydic.portal.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tydic.borderer.domain.BorderAgent;
import com.tydic.borderer.domain.BordererInfo;
import com.tydic.borderer.domain.bo.AddBordererAgentBo;
import com.tydic.borderer.domain.bo.BorderAgentByPageBo;
import com.tydic.borderer.domain.bo.RenewContractBo;
import com.tydic.borderer.mapper.BorderAgentMapper;
import com.tydic.borderer.service.IAgentContractService;
import com.tydic.borderer.service.IBorderAgentService;
import com.tydic.borderer.service.IBordererInfoService;
import com.tydic.common.core.domain.R;
import com.tydic.common.core.domain.model.LoginUser;
import com.tydic.common.core.enums.AgentApplyStatusEnum;
import com.tydic.common.core.enums.SignStatusEum;
import com.tydic.common.core.enums.UserTypeEnum;
import com.tydic.common.core.exception.api.ApiException;
import com.tydic.common.core.utils.PinyinUtils;
import com.tydic.common.mybatis.core.page.TableDataInfo;
import com.tydic.common.satoken.utils.LoginHelper;
import com.tydic.common.web.domain.FileItem;
import com.tydic.system.service.ISysMessageService;
import com.tydic.system.service.ISysOssService;
import com.tydic.system.service.ISysUserService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 边民代表管理
 *
 * @author zr
 * @date 2023-10-07 16:36
 */
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/portal/borderAgent")

public class BorderAgentController {

    private final IBorderAgentService borderAgentService;

    private final IBordererInfoService bordererInfoService;


    private final IAgentContractService agentContractService;

    private final ISysMessageService messageService;

    private final ISysOssService sysOssService;

    private final BorderAgentMapper borderAgentMapper;

    private final ISysUserService sysUserService;

    /**
     * 边民代表申请边民委托代理
     */
    /**
     * 边民代表申请边民委托代理
     */
    @PostMapping(value = "/applyBorder")
    public R applyBorder(@RequestBody AddBordererAgentBo request) {
        return R.ok();
    }

    /**
     * 边民邀请边民代表成为委托人
     */
    /**
     * 边民邀请边民代表成为委托人
     */
    @PostMapping(value = "/borderInvite")
    public R borderInvite(@RequestBody AddBordererAgentBo request) {

        String signUrl = borderAgentService.inviteBorderer(request);
        return R.ok("签署链接", signUrl);
    }


    /**
     * 边民续签
     */
    @PostMapping(value = "/borderRenew")
    public R borderRenew(@RequestBody @Valid RenewContractBo request) {
        String signUrl = borderAgentService.renewContract(request);
        return R.ok("签署链接", signUrl);
    }

    /**
     * 搜索边民信息 (根据边民号查询)
     */
    /**
     * 搜索边民
     */
    @GetMapping(value = "/searchBorder")
    public R searchBorder(String bordererCardNumber) {
        //根据姓名、手机号搜索边民
        BordererInfo bordererInfoAgent = bordererInfoService.queryBorderInfo(bordererCardNumber);
        return R.ok(bordererInfoAgent);
    }


    /**
     * 已委托代理的边民列表
     */
    /**
     * 已委托代理的边民列表
     */
    @PostMapping(value = "/borderList")
    public R borderList(@RequestBody BorderAgentByPageBo request) {
        //当前边民代表登录信息
        LoginUser currentUser = LoginHelper.getLoginUser();
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(currentUser.getUserCode());
        request.setAgentCardNumber(bordererInfo.getBordererCardNumber());
        Page<BorderAgent> list = borderAgentService.queryAduitSymbolList(request);
        return R.ok(TableDataInfo.build(list));
    }

    /**
     * 已委托代理的边民列表（发布商品）
     */
    @PostMapping(value = "/myBorders")
    public R myBorders(@RequestBody BorderAgentByPageBo request) {
        //当前边民代表登录信息
        LoginUser currentUser = LoginHelper.getLoginUser();
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(currentUser.getUserCode());
        request.setAgentCardNumber(bordererInfo.getBordererCardNumber());
        QueryWrapper<BorderAgent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("agent_borderer_id", bordererInfo.getId());
        queryWrapper.in("apply_status", AgentApplyStatusEnum.AGREE.getStatus(), AgentApplyStatusEnum.REVOKING.getStatus(), AgentApplyStatusEnum.NEAR_THE_EXPIRE_DATE.getStatus());
        queryWrapper.eq("apply_contract_status", SignStatusEum.SIGNED.getStatus());
        List<String> bordererInfoIds = borderAgentMapper.selectList(queryWrapper).stream().map(BorderAgent::getBordererId).collect(Collectors.toList());
        if (CollUtil.isEmpty(bordererInfoIds)) {
            return R.ok(new Page<BorderAgent>());
        }
        // 把边民代表自己加入
        bordererInfoIds.add(0, bordererInfo.getId());
        Page<BordererInfo> bordererInfoPage = bordererInfoService.pageByIds(request.getPageNo(), request.getPageSize(), bordererInfoIds);
        bordererInfoPage.getRecords().sort((o1, o2) -> {
            if (o1 == null) {
                return 1;
            }
            if (o2 == null) {
                return -1;
            }
            if (StrUtil.equals(o1.getId(), bordererInfo.getId())) {
                return -1;
            }
            if (StrUtil.equals(o2.getId(), bordererInfo.getId())) {
                return 1;
            }
            String fullSpell1 = PinyinUtils.getFullSpell(o1.getName());
            String fullSpell2 = PinyinUtils.getFullSpell(o2.getName());
            return fullSpell1.compareTo(fullSpell2);
        });
        return R.ok(TableDataInfo.build(bordererInfoPage));
    }

    /**
     * 已委托代理的边民列表
     */
    /**
     * 已委托代理的边民列表
     */
    @PostMapping(value = "/borderAgentList")
    public R borderAgentList(@RequestBody BorderAgentByPageBo request) {
        //当前边民代表登录信息
        LoginUser currentUser = LoginHelper.getLoginUser();
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(currentUser.getUserCode());
        request.setAgentCardNumber(bordererInfo.getBordererCardNumber());
        BorderAgent byBordererId = borderAgentService.findByAgentBordererId(bordererInfo.getId());
        if (byBordererId == null) {
            return R.ok(new Page<BorderAgent>());
        }
        Page<BorderAgent> list = borderAgentService.queryAduitAgentList(request);
        return R.ok(TableDataInfo.build(list));
    }

    /**
     * 同意委托代理
     */
    /**
     * 同意委托代理
     */
    @GetMapping(value = "/agree")
    public R agree(@NotBlank(message = "请求参数不能为空") String id) {
        return R.ok("签署链接", borderAgentService.agree(id));
    }

    /**
     * 拒绝委托代理
     */
    /**
     * 拒绝委托代理
     */
    @GetMapping(value = "/refuse")
    public R refuse(@NotBlank(message = "请求参数不能为空") String id) {
        borderAgentService.refuse(id);
        return R.ok();
    }

    /**
     * 解除委托
     *
     * @param bordererId 边民成员id
     * @return
     */
    /**
     * 解除委托
     */
    @GetMapping(value = "/remove")
    public R remove(@NotBlank(message = "请求参数不能为空") String bordererId) {
        borderAgentService.remove(bordererId);
        return R.ok();
    }

    /**
     * 同意解除
     *
     * @param categoryId
     * @return
     */
    /**
     * 同意解除
     */
    @GetMapping(value = "/agreeRemove")
    public R agreeRemove(@NotBlank(message = "请求参数不能为空") String categoryId) {
        borderAgentService.agreeRemove(categoryId);
        return R.ok();
    }

    /**
     * 拒绝委托代理
     */
    /**
     * 拒绝解除授权
     */
    @GetMapping(value = "/refuseRemove")
    public R refuseRemove(@NotBlank(message = "请求参数不能为空") String categoryId) {
        borderAgentService.refuseRemove(categoryId);
        return R.ok();
    }

    /**
     * 查询详情
     */
    /**
     * 查询边民详情
     */
    @GetMapping(value = "/queryBordererDetail")
    public R queryBordererDetail(String userCode) {
        if (userCode == null) {
            throw new ApiException("请求参数不能为空");
        }
        BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(userCode);
        if (bordererInfo == null) {
            throw new ApiException("当前边民信息不存在");
        }
        LambdaQueryWrapper<BorderAgent> lqw = Wrappers.lambdaQuery(BorderAgent.class).eq(BorderAgent::getBordererId, bordererInfo.getId()).in(BorderAgent::getApplyStatus, AgentApplyStatusEnum.AGREE.getStatus(), AgentApplyStatusEnum.REVOKING.getStatus(), AgentApplyStatusEnum.NEAR_THE_EXPIRE_DATE.getStatus()).eq(BorderAgent::getApplyContractStatus, SignStatusEum.SIGNED.getStatus());
        BorderAgent borderAgent = borderAgentMapper.selectOne(lqw, false);
        return R.ok(borderAgent);
    }

    /**
     * 查询详情
     */
    /**
     * 查询边民代表详情
     */
    @GetMapping(value = "/queryAgentDetail")
    public R queryAgentDetail(String id) {
        if (id == null) {
            throw new ApiException("请求参数不能为空");
        }
        BorderAgent borderAgent = borderAgentMapper.selectById(id);
        return R.ok(borderAgent);
    }


    /**
     * 获取签署链接
     */
    /**
     * 获取签署链接
     */
    @GetMapping(value = "/getSignUrl")
    public R getSignUrl(String id) {
        String signUrl = borderAgentService.getSignUrl(id);
        return R.ok("签署链接", signUrl);
    }


    /**
     * 预览合同
     */
    @GetMapping("/getContractPageView")
    /**
     * 预览合同
     */
    public void getContractPageView(String agentId, HttpServletResponse response) {
        if (agentId == null) {
            throw new ApiException("请求参数不能为空");
        }
        borderAgentService.getContractPageView(agentId, response);
    }


    /**
     * 合同填充
     */
    /**
     * 合同填充
     */
    @GetMapping(value = "/fillContent")
    public R fillContent(String id) {
        BorderAgent borderAgent = new BorderAgent();
        borderAgent.setId(id);
        BorderAgent byBordererId = borderAgentService.findByBordererId(borderAgent);

        FileItem fileItem = borderAgentService.fillContract(byBordererId);
        String contractFileId = String.valueOf(sysOssService.upload(fileItem.getData(), fileItem.getFileName(), fileItem.getContentType()).getOssId());
        return R.ok(contractFileId);
    }

    /**
     * 合同上传与信息更新
     */
    /**
     * 合同上传与信息更新
     */
    @GetMapping(value = "/uploadAndUpdate")
    public R uploadAndUpdate(String id) {
        BorderAgent borderAgent = new BorderAgent();
        borderAgent.setId(id);
        BorderAgent byBordererId = borderAgentService.findByBordererId(borderAgent);
        borderAgentService.uploadAndUpdate(byBordererId);
        return R.ok(borderAgent);
    }


    /**
     * 创建并推送签署
     */
    /**
     * 创建并推送签署
     */
    @GetMapping(value = "/createAndPush")
    public R createAndPush(String id) {
        BorderAgent borderAgent = new BorderAgent();
        borderAgent.setId(id);
        BorderAgent byBordererId = borderAgentService.findByBordererId(borderAgent);
        boolean andPush = borderAgentService.createAndPush(byBordererId);
        return R.ok(andPush);
    }

    /**
     * 申请成为边民代表
     */
    @GetMapping(value = "/applyBordererAgent")
    public R applyBordererAgent() {
        LoginUser currentUser = LoginHelper.getLoginUser();
        sysUserService.updateUserType(currentUser.getUserCode(), UserTypeEnum.BORDERER_AGENT.getUserType());
        return R.ok("申请边民代表成功");
    }
}
